<template>
  <div class="hawkContent">
    <hawk-breadcrumb></hawk-breadcrumb>
    <el-row :gutter="20" style="padding-left: 20px">
      <el-col :span="5" style="display: flex; align-items: center">
        <span style="width: 90px; color: #666666; font-size: 13px">地区名称：</span>
        <el-input placeholder="请输入地区名称搜索" v-model="queryForm.query.name">
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="hawkSearch" @click="init(true)">搜索</el-button>
        <el-button plain @click="reSet">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right; text-align: right; padding-right: 30px">
        <el-button type="hawkCreate" @click="edit">添加地区</el-button>
      </el-col>
    </el-row>
    <!-- { key: 'createTime', label: '添加时间' }, -->
    <hawk-table v-model="multipleSelection" :table-data="tableData"
                :page="queryForm.page" :number="true"
                @selectionChange="handleSelectionChange" :options="[
        { key: 'name', label: '地区名称' },
        { key: 'handle', label: '操作' },
      ]">
      <template #createTime="{ row }">
        <span>{{ transformDateFormat(row.createTime, 'yyyy-MM-dd hh:mm:ss') }}</span>
      </template>
      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="edit(row)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="del(row)">删除</span>
      </template>
    </hawk-table>
    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="catchDel">批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="formTitle" :visible.sync="addDialogVisible" width="20%"
               :close-on-click-modal="false" @close="addDialogClosed">
      <!-- 内容主题区 -->
      <el-form :model="addForm" label-position="right" :rules="addFormRules"
               ref="addFormRef" label-width="90px">
        <el-form-item label="地区名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
/**
 * @author 创建者
 * @description 文件描述
 * @api 后台接口地址
 * @since 文件生成时间
 * @update 代码更新时间
 * @modifier 修改人
 * @bug bug名称或无
 * @version 版本号 例:v1.0.0
 */
import {
  getList,
  doDelete,
  doAdd,
  doEdit,
  isAreaExists,
  searchList,
} from '@/api/assets/dictionaries/area'

export default {
  data () {

    let inHaveName = async (rule, value, callback) => {

      let ret = await isAreaExists(value)
      console.log(ret);

      if (ret.code == 998) {
        callback()
      } else {
        callback(new Error('名称已经存在'))
      }

    }


    return {
      multipleSelection: [],
      addDialogVisible: false,
      formTitle: '',
      total: 0,
      queryForm: {
        query: {
          name: '',
        },
        page: {
          current: 1,
          size: 10,
        },
      },

      tableData: [],
      addForm: {
        id: '',
        name: '',
        createTime: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入地区名称', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '地区名称的长度在2-20个字符之间',
            trigger: 'blur',
          },
          { validator: inHaveName, trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    //重置
    reSet () {
      this.queryForm.query = this.$options.data().queryForm.query
      this.init()
    },
    //调接口
    async init (type) {
      if (type) this.queryForm.page.current = 1;
      this.multipleSelection = []

      const { data } = await getList(this.queryForm)
      console.log(data);
      this.tableData = data.records
      this.total = data.total
    },
    // 展示条数
    handleSizeChange (val) {
      this.queryForm.page.size = val
      this.init()
    },
    //展示页码
    handleCurrentChange (val) {
      this.queryForm.page.current = val
      this.init()
    },
    //多选
    handleSelectionChange (val) {
      this.multipleSelection = val
      // console.log(this.multipleSelection)
    },
    catchDel () {

      console.log('-----xxxxx------');

      let list = []
      this.multipleSelection.forEach((item) => {
        list.push(item.id)
      })
      console.log(list);
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete(list)
          console.log(ret, '--------------ret----');

          if (ret.code == 20000) {

            let type = ''
            
            if (ret.data || ret.message.indexOf('成功') != -1) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }

            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.multipleSelection.length == this.tableData.length) {

              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }

            }

            this.multipleSelection = []
            console.log('-------------init---');
            this.init()

          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    edit (row) {
      if (!row.id) {
        this.formTitle = '添加地区'
      } else {
        this.formTitle = '修改地区信息'
        this.addForm = Object.assign({}, row)
        // console.log(this.addForm)
      }
      this.addDialogVisible = true
    },
    addDialogClosed () {
      this.addForm = this.$options.data().addForm
      this.$refs.addFormRef.resetFields()
      this.init()
      this.addDialogVisible = false
    },
    save () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        console.log(this.addForm);
        if (this.addForm.id) {
          console.log("edit");
          let { message } = await doEdit({
            "id": this.addForm.id,
            "name": this.addForm.name
          })
          this.$msg.success(message)
          this.multipleSelection = []
        } else {
          // 添加地区
          console.log("new");
          let { message } = await doAdd({
            "id": 0,
            "name": this.addForm.name
          })
          this.multipleSelection = []
          this.$msg.success(message)
        }
        this.addDialogClosed()
      })
    },
    del (row) {

      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete([row.id])
          if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }
            this.multipleSelection = []
            this.init()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })


    },
  },
  mounted () {
    this.init()
    // this.searchData()
  },
}
</script>
<style lang="scss" scoped>
</style>
